package vip.xumy.admin.sys.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vip.xumy.admin.sys.mapper.IDictTypeMapper;
import vip.xumy.admin.sys.mapper.IDictionaryMapper;
import vip.xumy.admin.sys.pojo.Dictionary;
import vip.xumy.core.exception.CoreException;
import vip.xumy.core.utils.StringUtil;

/**
 * @author:mengyxu
 * @date:2019年12月6日
 */

@Service
public class DictionaryService {
	@Autowired
	private IDictionaryMapper dictMapper;
	@Autowired
	private IDictTypeMapper dictTypeMapper;

	public List<Dictionary> queryType(Dictionary example) {
		return dictTypeMapper.queryType(example);
	}

	public void save(Dictionary dict) {
		if (StringUtil.isEmpty(dict.getParent())) {
			dictTypeMapper.insertType(dict);
		} else {
			dictMapper.insertDict(dict);
		}
	}

	public void update(Dictionary dict) {
		if (StringUtil.isEmpty(dict.getParent())) {
			dictTypeMapper.updateType(dict);
		} else {
			dictMapper.updateDict(dict);
		}
	}

	@Transactional
	public void delete(Dictionary dict) throws CoreException{
		Integer id = dict.getId();
		String code = dict.getCode();
		if (id != null) {
			dictMapper.deleteDict(id);
		} else {
			dictTypeMapper.deleteType(code);
			dictMapper.deleteDicts(code);
		}
	}

	public Map<String, List<Dictionary>> getDicts(String[] codes) {
		if (codes == null || codes.length == 0) {
			return null;
		}
		Map<String, List<Dictionary>> map = new HashMap<>();
		for (String code : codes) {
			map.put(code, getDict(code));
		}
		return map;
	}

	public List<Dictionary> getDict(String code) {
		Dictionary example = new Dictionary();
		example.setStatus("A");
		example.setParent(code);
		return dictMapper.queryDict(example);
	}

}
